<template>
  <div class="contract-editor-container">
    <!-- 工具栏 -->
    <el-card class="mb-4">
      <div class="flex justify-between items-center">
        <el-text v-if="!show"> 清 账 承 诺 书</el-text>
        <h1 v-else> {{labor.title}}</h1>
        <div class="flex gap-2">
          <el-button type="primary" @click="saveContract">
            保存合同
          </el-button>
          <el-button @click="previewContract">
            预览
          </el-button>
        </div>
        <div>
        </div>
      </div>
    </el-card>
    
    <!-- 合同编辑区域 -->
    <el-card v-if="show">
      <div class="contract-content">
        <!-- 合同标题 -->
        <div class="text-center mb-8">
          <h1 class="text-2xl font-bold">服务合同</h1>
          <p class="text-left">合同编号: {{ contract.contractNumber }}</p>
        </div>
        
        <!-- 合同双方信息 -->
        <div class="mb-6">
          <div class="grid grid-cols-2 gap-6">
              <p class="font-medium">致： 苏州华雨建设科技有限公司</p>
          </div>
        </div>

        <div class="mb-6">
          <h2 class="text-xl font-semibold mb-4 border-b pb-2">一、工程概况和内容</h2>
          <p>　　我
            <span class="edit" :contenteditable="isEdit('partyB')" 
                 @input="onChange('partyB', $event.target)">
                {{ contract.partyB }}
              </span>确认：身份证号码：
              <span class="edit" :contenteditable="isEdit('idcard')" 
                 @input="onChange('idcard', $event.target)">
                {{ contract.idcard }}
              </span>，我于
              <span class="edit" :contenteditable="isEdit('date')" 
                 @input="onChange('date', $event.target)">
                {{ contract.date }}
              </span>
              日在贵司
              <span class="edit" :contenteditable="isEdit('project')" 
                 @input="onChange('project', $event.target)">
                {{ contract.project }}
              </span>
              项目承包的
              <span class="edit" :contenteditable="isEdit('scop')" 
                 @input="onChange('scop', $event.target)">
                {{ contract.scop }}
              </span>
              辅料及工作期间所有工资、报销等费用全部结算支付完毕（结算工资
              <span class="edit" :contenteditable="isEdit('settlement')" 
                 @input="onChange('settlement', $event.target)">
                {{ contract.settlement }}
              </span>
              ，报销费用
              <span class="edit" :contenteditable="isEdit('reimbursement')" 
                 @input="onChange('reimbursement', $event.target)">
                {{ contract.reimbursement }}
              </span>
              元，共计
              <span class="edit" :contenteditable="isEdit('price')" 
                 @input="onChange('price', $event.target)">
                {{ contract.price }}
              </span>
              元），我无任何理由再向贵司要求其他任何款项，否则贵司有权追究我的刑事责任。</p>
        </div>

        <div class="mb-6">
          <p>剩余<span class="edit" :contenteditable="isEdit('remaining')" 
                 @input="onChange('remaining', $event.target)">
                {{ contract.remaining }}
              </span> 元于<span class="edit" :contenteditable="isEdit('pay_date')" 
                 @input="onChange('pay_date', $event.target)">
                {{ contract.pay_date }}
              </span>前支付如下账户：</p>
          <p>姓名：<span class="edit" :contenteditable="isEdit('partyB')" @input="onChange('partyB', $event.target)">{{ contract.partyB }}</span></p>
          <p>开户行：<span class="edit" :contenteditable="isEdit('bank')" @input="onChange('bank', $event.target)">{{ contract.bank }}</span></p>
          <p>账号：<span class="edit" :contenteditable="isEdit('bank_number')" @input="onChange('bank_number', $event.target)">{{ contract.bank_number }}</span></p>
          <p>开户行号：<span class="edit" :contenteditable="isEdit('bank_code')" @input="onChange('bank_code', $event.target)">{{ contract.bank_code }}</span></p>
        </div>

        <div class="mb-6">
          <p>　　特此承诺！</p>
        </div>

        <el-row>
            <el-col :span="18"></el-col>
            <el-col :span="6">
              <p>承 诺 人(签字及按手印)：</p>
              <p>联系电话：：</p>
              <p>日期：</p>
            </el-col>
          </el-row>
        <!-- ------------------------------------------------------------ -->
      </div>
    </el-card>
    
    <!-- 预览弹窗 -->
    <el-dialog v-model="previewVisible" title="合同预览" width="80%">
      <div class="contract-preview" >
        <!-- 预览内容与编辑区域相同，但所有内容都不可编辑 -->
        <div ref="pdfContent" v-html="previewHtml" class="contract-content" />
      </div>
      
      <template #footer>
        <el-button type="primary" @click="exportToPdf">导出为PDF</el-button>
        <el-button @click="previewVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { ElMessage, ElCard, ElButton, ElDialog } from 'element-plus';
import html2pdf from 'html2pdf.js';
import http from '../../../util/request';
const pdfContent = ref(null);

const show = ref(false)
const labor = ref({id:0,title:'',is:false});
let is = sessionStorage.getItem('labor_contract');
if(is){
  show.value = true
  labor.value = JSON.parse(is)
}
// 初始化合同数据
const contract = ref<any>({
  project: '上海市浦东新区浦东南路 877 号、879 号、889 号、897 号LG 层（即地下一层）LG09A-1 单元商铺装修工程',
  partyB: '陈应林',
  idcard: '320826198911083010',
  scop:'木工收尾',
  date: '2024 年   05 月 01 日至  2024 年   05 月  06 日',
  settlement: '3800.00',
  reimbursement: '0.00',
  price: '3800.00',
  remaining: '1000.00',
  pay_date: '2024年5月08日',
  bank: '中国工商银行陕西省分行长安区支行',
  bank_number: '6215581310001550779',
  bank_code: '45536352534633424',
});

// 可编辑区域设置
const dialogVisible = ref(false);
const editableSections = ref<string[]>([
  'project',
  'partyB',
  'idcard',
  'scop',
  'date',
  'settlement',
  'reimbursement',
  'price',
  'remaining',
  'pay_date',
  'bank',
  'bank_number',
  'bank_code',
]);


// 状态管理
const isSaved = ref(false);
const previewVisible = ref(false);
const previewHtml = ref('');

// 判断区域是否可编辑
const isEdit = (section: string) => {
  return editableSections.value.includes(section);
};

// 处理内容变化
const onChange = (section:any, value: any) => {
  contract.value[section] = value.innerText;
  isSaved.value = false;
};

const getData = () => {
    http.post('/labor/template',{labor_contract_id:labor.value.id,type:'temp'}).then((response:any)=>{
      if(response.data.data){
        contract.value = response.data.data.content
        labor.value.is = true
      }
      dialogVisible.value = true;
    })
}

// 保存合同
const saveContract = () => {
  // 模拟保存操作
  let request:any = null
  let content:string = JSON.stringify(contract.value)
    if(labor.value.is){
        request = http.patch('/labor/template',{labor_contract_id:labor.value.id,type:'temp',content:content})
    }else{
        request = http.put('/labor/template',{labor_contract_id:labor.value.id,type:'temp',content:content})
    }
    request.then((response:any)=>{
      if(response.data.code == 200){
        isSaved.value = true;
        ElMessage.success('合同已保存');
        labor.value.is = true
      }
    })
};

// 预览合同
const previewContract = () => {
  // 生成预览HTML，将所有可编辑区域变为不可编辑
  const tempDiv = document.createElement('div');
  const contractContent = document.querySelector('.contract-content')?.cloneNode(true);
  
  if (contractContent) {
    tempDiv.appendChild(contractContent);
    const editableElements = tempDiv.querySelectorAll('.edit');
    editableElements.forEach(el => {
      (el as HTMLElement).contentEditable = 'false';
      el.removeAttribute('class');
    });
    previewHtml.value = tempDiv.innerHTML;
    previewVisible.value = true;
  }
};

// 页面加载时显示可编辑区域设置按钮
onMounted(() => {
  getData();
});

// 导出PDF的方法
const exportToPdf = () => {
  if (!pdfContent.value) return;

  // 配置选项
  const opt = {
    margin: 10,
    filename: '导出的文档.pdf',
    image: { type: 'jpeg', quality: 0.98 },
    html2canvas: { scale: 2, useCORS: true },
    jsPDF: { unit: 'mm', format: 'a4', orientation: 'portrait' }
  };

  // 生成PDF
  html2pdf().from(pdfContent.value).set(opt).save();
};
</script>

<style scoped>
.contract-editor-container {
  padding: 20px;
  height: calc(100vh - 25vh);overflow-y: scroll;
}

.contract-content {
  line-height: 1.8;
  font-size: 16px;
}

.edit {
  border-bottom: 1px dashed #edd32c;
  padding: 0 4px;
  min-width: 60px;
  display: inline-block;
}

.edit[contenteditable="true"] {
  background-color: #edd32c;
  cursor: text;
}

.edit[contenteditable="true"]:focus {
  outline: 1px solid #edd32c;
  border-radius: 2px;
}

.contract-preview {
  max-height: 70vh;
  overflow-y: auto;
  padding: 20px;
}
</style>
